const { mysqlQuery } = require('./mysql.js');
const { checkIp, checkPort } = require('./common.js');
const GetServerList = (req, res) => {
    mysqlQuery("select * from server_list").then(response => {
        res.json({ status: true, data: response })
    }).catch(e => {
        res.json({ status: false, msg: e })
    })
}

const AddServerList = (req, res) => {
    let params = req.body;
    let name = typeof params.name != 'undefined' ? params.name : '';
    let ip = typeof params.ip != 'undefined' ? params.ip : '';
    let port = typeof params.port != 'undefined' ? params.port : '8888';
    let token = typeof params.token != 'undefined' ? params.token : '';
    if (ip === '' || !checkIp(ip)) {
        res.json({ status: false, msg: 'ip参数错误' });
        return;
    }
    if (!checkPort(port)) {
        res.json({ status: false, msg: 'port参数错误' });
        return;
    }
    if (token === '') {
        res.json({ status: false, msg: 'token参数错误' });
        return;
    }
    mysqlQuery("INSERT INTO server_list(name,ip,port,token) VALUES(?,?,?,?)", [name, ip, port, token]).then(response => {
        res.json({ status: true, data: response })
    }).catch(e => {
        res.json({ status: false, msg: e })
    })
}

const UpdateServerList = (req, res) => {
    let params = req.body;
    let id = typeof params.id != 'undefined' ? params.id : '';
    let name = typeof params.name != 'undefined' ? params.name : '';
    let ip = typeof params.ip != 'undefined' ? params.ip : '';
    let port = typeof params.port != 'undefined' ? params.port : '8888';
    let token = typeof params.token != 'undefined' ? params.token : '';
    if (id === '') {
        res.json({ status: false, msg: 'id参数错误' });
        return;
    }
    if (ip === '' || !checkIp(ip)) {
        res.json({ status: false, msg: 'ip参数错误' });
        return;
    }
    if (!checkPort(port)) {
        res.json({ status: false, msg: 'port参数错误' });
        return;
    }
    if (token === '') {
        res.json({ status: false, msg: 'token参数错误' });
        return;
    }
    mysqlQuery("UPDATE server_list SET name = ?,ip = ?,port = ?,token = ? WHERE id = ?", [name, ip, port, token, id]).then(response => {
        res.json({ status: true, data: response })
    }).catch(e => {
        res.json({ status: false, msg: e })
    })
}

const DelServerList = (req, res) => {
    let params = req.body;
    let id = typeof params.id != 'undefined' ? params.id : '';
    if (id === '') {
        res.json({ status: false, msg: 'id参数错误' });
        return;
    }
    mysqlQuery("DELETE FROM server_list WHERE id = ?", [id]).then(response => {
        res.json({ status: true, data: response })
    }).catch(e => {
        res.json({ status: false, msg: e })
    })
}

module.exports = {
    GetServerList,
    AddServerList,
    UpdateServerList,
    DelServerList
}